package cqrtplm.aop;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hustcad.plm.basic.util.TyplmEntityBaseUtil;
import com.hustcad.plm.pdm.ec.module.dto.TyplmChangeIssueDTO;
import com.hustcad.plm.pdm.form.model.dto.FormDataDTO;
import com.hustcad.plm.pdm.user.service.TyplmOrgService;
import com.hustcad.plm.pdm.user.service.TyplmPrincipalService;
import com.ty.basic.constant.TableTypeConstrant;
import com.ty.basic.entity.PrincipalEntity;
import com.ty.basic.entity.org.OrgDO;
import com.ty.basic.entity.org.UserDO;
import com.ty.basic.session.TyAccountContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigInteger;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Aspect
@Component
@Slf4j
public class CreateFormDataAop {

    @Resource
    private TyplmPrincipalService typlmPrincipalService;

    @Resource
    private TyplmOrgService typlmOrgService;

    /**
     * 创建表单时，给表单中的 DocumentNumberForm 字段赋值
     * @param proceedingJoinPoint
     * @return
     * @throws Throwable
     */
    @Around("execution(* com.hustcad.plm.pdm.form.service.impl.TyFormDataExtServiceImpl.createFormDataWithFile(com.hustcad.plm.pdm.form.model.dto.FormDataDTO, " +
            "java.util.List<com.hustcad.plm.pdm.form.model.dto.FormDataFileMarkDTO>, java.util.List<org.springframework.web.multipart.MultipartFile>," +
            " com.hustcad.plm.pdm.formusage.model.dto.FormFileDTO))")
    public Object createFormDataWithFile(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        Object[] args = proceedingJoinPoint.getArgs();
        FormDataDTO formDataDTO = (FormDataDTO) args[0];
        String formDataStr = formDataDTO.getFormDataStr();
        JSONObject formDataJson = JSONObject.parseObject(formDataStr);
        UserDO user = TyAccountContext.getUser();
        List<PrincipalEntity> outParent = typlmPrincipalService.getOneOutParentOrg(
                new PrincipalEntity(user.getOid(), TableTypeConstrant.TY_USER_OTYPE)
        );
        String str = "";
        typlmOrgService.dealOrgParentPath(outParent);
        boolean flag = false;
        for(PrincipalEntity outParentEntity : outParent){
            OrgDO orgDO = (OrgDO) outParentEntity;
            String parentPath = orgDO.getParentPath();
            if(StringUtils.isNotBlank(parentPath)){
                flag = true;
                str = parentPath;
            }
        }
        if(!flag){
            for(PrincipalEntity outParentEntity : outParent){
                OrgDO orgDO = (OrgDO) outParentEntity;
                String displayFullName = orgDO.getDisplayFullName();
                if(!"润通科技".equals(displayFullName)){
                    str = displayFullName;
                }
            }
        }
        processJsonObject(formDataJson,"DocumentNumberForm",formDataDTO.getObjectNumber());
        processJsonObject(formDataJson,"ApplicationDepartment",str);
        formDataDTO.setFormDataStr(formDataJson.toJSONString());
        return proceedingJoinPoint.proceed();
    }

    /**
     * 编辑页面增加逻辑处理
     *
     * @param proceedingJoinPoint
     * @return
     * @throws Throwable
     */
    @Around("execution(* com.hustcad.plm.pdm.ec.service.impl.TyplmChangeIssueServiceImpl.createChangeIssueAndEcLink(com.hustcad.plm.pdm.ec.module.dto.TyplmChangeIssueDTO))")
    public Object createChangeIssueAndEcLink(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        TyplmChangeIssueDTO typlmChangeIssueDTO = (TyplmChangeIssueDTO)proceedingJoinPoint.getArgs()[0];
        String formDataStr = typlmChangeIssueDTO.getFormData();
        JSONObject formDataJson = JSONObject.parseObject(formDataStr);
        JSONObject jsonObject = formDataJson.getJSONObject("FeedbackPerson");
        if(CollUtil.isNotEmpty(jsonObject)){
            BigInteger userId = jsonObject.getBigInteger("oid");
            List<PrincipalEntity> outParent = typlmPrincipalService.getOneOutParentOrg(
                    new PrincipalEntity(userId, TableTypeConstrant.TY_USER_OTYPE)
            );
            typlmOrgService.dealOrgParentPath(outParent);
            boolean flag = false;
            for(PrincipalEntity outParentEntity : outParent){
                OrgDO orgDO = (OrgDO) outParentEntity;
                String parentPath = orgDO.getParentPath();
                if(StringUtils.isNotBlank(parentPath)){
                    flag = true;
                    jsonObject.put("FeedbackDepartment", parentPath);
                }
            }
            if(!flag){
                for(PrincipalEntity outParentEntity : outParent){
                    OrgDO orgDO = (OrgDO) outParentEntity;
                    String displayFullName = orgDO.getDisplayFullName();
                    if(!"润通科技".equals(displayFullName)){
                        jsonObject.put("FeedbackDepartment", displayFullName);
                    }
                }
            }
            typlmChangeIssueDTO.setFormData(jsonObject.toJSONString());
        }
        return proceedingJoinPoint.proceed();
    }

    private void processJsonObject(JSONObject jsonObject, String formDataStr, String formDataValue) {
        for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();
            if (value instanceof JSONObject) {
                processJsonObject((JSONObject) value, formDataStr, formDataValue); // 递归处理嵌套对象
            }else if (value instanceof JSONArray) {
                processJsonArray((JSONArray) value, formDataStr, formDataValue); // 处理数组
            }else if (value instanceof String) {
                if(formDataStr.equals(key)){
                    jsonObject.put(key, formDataValue);
                }
            }
        }
    }

    private void processJsonArray( JSONArray jsonArray, String formDataStr, String formDataValue) {
        for (Object item : jsonArray) {
            if (item instanceof JSONObject) {
                processJsonObject((JSONObject) item, formDataStr, formDataValue);
            } else if (item instanceof JSONArray) {
                processJsonArray((JSONArray) item, formDataStr, formDataValue);
            }
        }
    }

}

